package com.course.service.impl;

import com.course.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${file.upload.base-path}")
    private String baseUploadPath;

    @Value("${file.download.base-url}")
    private String baseDownloadUrl;

    private static final Set<String> ALLOWED_EXTENSIONS = new HashSet<>(Arrays.asList(
        "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx",
        "txt", "zip", "rar", "7z",
        "jpg", "jpeg", "png", "gif"
    ));

    @Override
    public String storeFile(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (!isAllowedFileType(originalFilename)) {
            throw new IllegalArgumentException("不支持的文件类型");
        }

        // 使用日期作为子目录
        String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        Path uploadDirPath = Paths.get(baseUploadPath, dateStr);
        
        // 创建目录
        Files.createDirectories(uploadDirPath);
        log.debug("创建上传目录: {}", uploadDirPath);

        // 生成唯一的文件名
        String fileExtension = StringUtils.getFilenameExtension(originalFilename);
        String newFilename = UUID.randomUUID().toString() + "." + fileExtension;
        
        // 构建目标路径
        Path targetPath = uploadDirPath.resolve(newFilename);
        log.debug("目标文件路径: {}", targetPath);
        
        // 直接将MultipartFile的内容写入目标文件
        file.transferTo(targetPath.toFile());
        log.info("文件保存成功: {}", targetPath);
        
        return targetPath.toAbsolutePath().toString();
    }

    @Override
    public boolean deleteFile(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return false;
        }

        try {
            Path path = Paths.get(filePath);
            log.debug("删除文件: {}", path);
            return Files.deleteIfExists(path);
        } catch (IOException e) {
            log.error("删除文件失败: {}", filePath, e);
            return false;
        }
    }

    @Override
    public String getFileUrl(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return null;
        }
        // 转换为URL路径
        Path path = Paths.get(filePath);
        String relativePath = Paths.get(baseUploadPath).relativize(path).toString().replace('\\', '/');
        return baseDownloadUrl + "/" + relativePath;
    }

    @Override
    public boolean isAllowedFileType(String filename) {
        if (StringUtils.isEmpty(filename)) {
            return false;
        }
        String extension = StringUtils.getFilenameExtension(filename);
        return extension != null && ALLOWED_EXTENSIONS.contains(extension.toLowerCase());
    }
}
